var http = require("http");
var formidable = require("formidable");
http.createServer(function(req,res){
    switch (req.method){
        case "GET":
            show(req,res);
            break;
        case "POST":
            upload(req,res);
            break;
    }
}).listen(8899);

function show(req,res){
    var html = "<html><head><title>upload photos</title></head><body>" +
        '<form method="post" action="/" enctype="multipart/form-data">' +
        "<input type='text' name='name' />" +
        "<input type='file' name='file'>" +
        '<p><input type="submit" value="Upload" /></p>' +
        "</form>" +
        "</body></html>";
    res.setHeader("Content-Type","text/html");
    res.setHeader("Content-Length",Buffer.byteLength(html));
    res.end(html);
}

function upload(req,res){
    if(!isFormData(req)){
        res.statusCode = 400;
        res.end("Bad Request: expecting multipart/form-data");
        return;
    }
    var form = new formidable.IncomingForm();
    form.parse(req);
    /*form.on("field",function(field,value){
        console.log("field: " + field);
        console.log("value: " + value);
    });
    form.on("file",function(name,file){
        console.log("name: " + name);
        console.log(file);
    });
    form.on("end",function(){
        res.end("upload complete!");
    });*/
    form.parse(req,function(err,fields,files){
        console.log(fields);
        console.log(files);
        res.end("upload complete!");
    });
    form.on("progress",function(bytesReceived,bytesExpected){
        var percent = Math.floor(bytesReceived / bytesExpected * 100);
        console.log(percent);
    });
}

function isFormData(req){
    var type = req.headers['content-type'] || '';
    return 0 == type.indexOf('multipart/form-data');
}